import React, {useEffect, useState} from 'react'
import moment from 'moment'
import {Button, Modal, Tag} from 'antd'
import {connect, useDispatch} from 'umi'
import SearchForm from '@/components/SearchForm'
import CustomTable from '@/components/Table'

const formItemLayout = {
	labelCol: {flex: '120px'},
	wrapperCol: {flex: '1'},
}
interface BasicsType {
	driverRewardRules: {outTableList: any; basic: any; carTypeList: any}
	routerQuery: any
}
function AssociatedModal({
	driverRewardRules: {outTableList, basic},
	routerQuery,
}: BasicsType) {
	const [total, setTotal] = useState()
	const [page, setPage] = useState({
		current: 1,
		size: 10,
	})
	const [tableList, setTableList] = useState<any[]>([])
	const [loading, setLoading] = useState<boolean>(false)
	const [isModalOpen, setIsModalOpen] = useState<boolean>(false)
	const [checkData, setCheckData] = useState<any[]>([])

	const dispatch = useDispatch()

	const formItems: any[] = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'input',
					label: '商品方案ID',
					name: 'commodityNo',
					key: 'commodityNo',
				},
				{
					type: 'input',
					label: '商品方案名称',
					name: 'commodityName',
					key: 'commodityName',
				},
				{},
			],
		},
	]

	// 数据勾选
	const editCar = (record: any, type: string) => {
		if (type === 'add') {
			const userData = tableList?.map((item: any) => {
				const newObject = item
				if (newObject.id === record?.id) {
					newObject.isSelect = true
				}
				return newObject
			})
			setTableList(() => userData)
			const newData = checkData || []
			newData.push(record)
			setCheckData(() => newData)
		} else {
			const userDataE = tableList?.map((item: any) => {
				const newObject = item
				if (newObject.id === record?.id) {
					newObject.isSelect = false
				}
				return newObject
			})
			setTableList(() => userDataE)
			const l = checkData?.filter((item: any) => item?.id !== record?.id)
			setCheckData(() => l)
		}
	}

	const columns: any[] = [
		{
			title: '序号',
			dataIndex: 'order',
			align: 'center',
			width: 70,
			render(text: any, record: any, index: any) {
				return <span>{(page.current - 1) * 10 + index + 1}</span>
			},
		},
		{
			title: '商品方案ID',
			dataIndex: 'commodityNo',
			key: 'commodityNo',
			width: 250,
			align: 'center',
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '商品方案名称',
			dataIndex: 'commodityName',
			key: 'commodityName',
			width: 150,
			align: 'center',
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '品牌/车系/车型',
			dataIndex: 'brandInfo',
			key: 'brandInfo',
			width: 250,
			align: 'center',
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '开始时间',
			dataIndex: 'beginTime',
			key: 'beginTime',
			width: 150,
			align: 'center',
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '结束时间',
			dataIndex: 'endTime',
			key: 'endTime',
			width: 150,
			align: 'center',
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '星级',
			dataIndex: 'carStar',
			key: 'carStar',
			width: 150,
			align: 'center',
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '订单类型',
			dataIndex: 'rentTypeName',
			key: 'rentTypeName',
			width: 150,
			align: 'center',
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '定金',
			dataIndex: 'depositAmount',
			key: 'depositAmount',
			width: 150,
			align: 'center',
			ellipsis: true,
			render: (text: any) => (text === -1 ? '--' : text),
		},
		{
			title: '押金',
			dataIndex: 'mortgageAmount',
			key: 'mortgageAmount',
			width: 150,
			align: 'center',
			ellipsis: true,
			render: (text: any) => (text === -1 ? '--' : text),
		},
		{
			title: '租期',
			dataIndex: 'leaseTerm',
			key: 'leaseTerm',
			width: 150,
			align: 'center',
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '月租金-新签',
			dataIndex: 'rentAmount',
			key: 'rentAmount',
			width: 150,
			align: 'center',
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '月租金-续签',
			dataIndex: 'renewRentAmount',
			key: 'renewRentAmount',
			width: 150,
			align: 'center',
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '首付款',
			dataIndex: 'advancePaymentAmount',
			width: 150,
			align: 'center',
			ellipsis: true,
			render: (text: any) => (text === -1 ? '--' : text),
		},
		{
			title: '尾款',
			dataIndex: 'balancePaymentAmount',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => (text === -1 ? '--' : text),
		},
		{
			title: '状态',
			dataIndex: 'auditStatus',
			key: 'auditStatus',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <Tag color="processing">{text}</Tag>,
		},
		{
			title: '操作',
			fixed: 'right',
			align: 'center',
			width: 180,
			render: (_: any, record: any) => (
				<>
					{record?.isSelect ? (
						<Button
							type="link"
							onClick={() => editCar(record, 'cancel')}>
							取消
						</Button>
					) : (
						<Button
							type="link"
							onClick={() => editCar(record, 'add')}>
							选择
						</Button>
					)}
				</>
			),
		},
	]

	/**
	 *
	 * @param value 获取表单的数据
	 */
	const getTabelValue = (values: any) => {
		setLoading(true)
		const params = {
			commoditySchemeWithBrandRentsTypesVO: {
				subjectId: basic?.subjectId,
				cityId: basic?.cityId ? basic?.cityId[1] : null,
				affiliatedCompanyId: basic?.orgId,
				rentTypeId: basic?.leaseType ? basic?.leaseType : null,
				auditStatusId: 1, // 审核状态 默认为通过
				schemeStatusId: 1, // 方案状态默认为有效
				brandIdList: basic.rewardModelList
					? basic?.rewardModelList
					: null,
				rentTypeIdList: [basic?.leaseType],
				leaseTermList: basic?.leaseTerm ? basic?.leaseTerm : null, // 租期
				beginTime:
					basic?.startTime &&
					moment(basic?.startTime).format('YYYY-MM-DD'),
				endTime:
					basic?.endTime &&
					moment(basic?.endTime).format('YYYY-MM-DD'),
				...values,
			},
			query: {
				...page,
				descs: 'update_time',
			},
		}
		dispatch({
			type: 'driverRewardRules/getRelevanceShop',
			payload: {...params},
			callback: (res: any) => {
				if (res?.success) {
					setTotal(res?.data?.total)
					const ids = outTableList?.map((item: any) => item?.id)
					const l = res?.data?.records?.map((item: any) => {
						const newObject = item
						if (ids?.includes(newObject?.id)) {
							newObject.isSelect = true
						}
						return newObject
					})
					setTableList(l)
				}
				setLoading(false)
			},
		})
	}

	useEffect(() => {
		if (basic?.subjectId) {
			getTabelValue({})
		}
	}, [page])

	const onFinish = (values: any) => {
		getTabelValue(values)
	}

	// 搜索重置
	const onReset = () => {
		const params = {
			current: 1,
			size: 10,
		}
		setPage(() => params)
		getTabelValue({})
	}

	const handleOk = () => {
		dispatch({
			type: 'driverRewardRules/updateState',
			payload: {
				outTableList: [...checkData],
			},
		})
		onReset()
		setIsModalOpen(false)
	}
	const handleCancel = () => {
		onReset()
		setIsModalOpen(false)
	}

	const showModal = () => {
		setIsModalOpen(true)
		setCheckData(() => outTableList)
		dispatch({
			type: 'driverRewardRules/updateState',
			payload: {
				basicCopy: basic,
			},
		})
		getTabelValue({})
	}
	return (
		<>
			{routerQuery.pageType !== 'detail' &&
			routerQuery.pageType !== 'process' ? (
				<Button
					style={{marginLeft: '10px'}}
					type="primary"
					size="small"
					disabled={
						!basic.subjectId ||
						!basic.orgId ||
						!basic.cityId ||
						!basic.rewardModelList ||
						!basic.leaseTerm ||
						!basic.leaseType ||
						!basic.startTime ||
						!basic.endTime
					}
					onClick={showModal}>
					新增
				</Button>
			) : null}
			<Modal
				title="关联商品方案"
				width={1400}
				open={isModalOpen}
				onOk={handleOk}
				onCancel={handleCancel}>
				<div>
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formItems}
						formLayout={formItemLayout}
					/>
					<div style={{marginTop: 30}}>
						<CustomTable
							params={page}
							columns={columns}
							total={total}
							scroll={{y: 400}}
							pagination
							callback={(pagination: any) => {
								setPage(pagination)
							}}
							loading={loading}
							dataSource={tableList}
						/>
					</div>
				</div>
			</Modal>
		</>
	)
}

export default connect(({driverRewardRules, user}: any) => ({
	user,
	driverRewardRules,
}))(AssociatedModal)
